package com.tanhua.server.interceptor;

import com.itheima.commons.util.JwtUtils;
import com.tanhua.model.domain.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 拦截器
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取到请求头
        String token = request.getHeader("Authorization");
        //使用工具类判断token是否有效
        boolean b = JwtUtils.verifyToken(token);
        if (!b){
            //如果token失效，返回401状态码
            response.setStatus(401);
            return false;
        }

        //解析token获取到id和phone
        Claims claims = JwtUtils.getClaims(token);
        Integer id = (Integer) claims.get("id");
        String phone = (String) claims.get("phone");
        //构造User对象，存入Threadlocal
        User user = new User();
        user.setId(Long.valueOf(id));
        user.setMobile(phone);
        UserHolder.set(user);

        return true;
    }


    //清空
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }

}
